package io.netty.example.mytest.nio.reactor;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;

/**
 * @ClassName NioServer
 * @Description 服务端
 * @Author dukezeng
 * @CreatedTime 2019/4/13 18:05
 * @Version 1.0
 **/
public class NioServer {
    public static final int SERVER_PORT = 8081;

    public void start(int port) throws Exception {
        //开启底层socket函数
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        //非阻塞读写io
        serverSocketChannel.configureBlocking(false);

        InitiationDispatcher dispatcher = new InitiationDispatcher();
        //绑定channel到selector
        dispatcher.registerChannel(SelectionKey.OP_ACCEPT, serverSocketChannel);

        dispatcher.registerHandler(SelectionKey.OP_ACCEPT, new AcceptEventHandler(
                        dispatcher.getDemultiplexer()));

        dispatcher.registerHandler(SelectionKey.OP_READ, new ReadEventHandler(
                        dispatcher.getDemultiplexer()));

        dispatcher.registerHandler(SelectionKey.OP_WRITE, new WriteEventHandler());

        dispatcher.handleEvents();
    }

    public static void main(String[] args) {
        try {
            new NioServer().start(SERVER_PORT);
            Thread.currentThread().join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
